package com.rongshu.sendmessage.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.Handler;
import android.os.Message;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class GetBitmapByURL {
    public static void getBitmap(final String url, final Handler handler) {
        final Bitmap[] bm = {null};
        try {
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    try{
                        URL iconUrl = new URL(url);
                        final URLConnection conn = iconUrl.openConnection();
                        HttpURLConnection http = (HttpURLConnection) conn;
                        int length = http.getContentLength();
                        conn.connect();
                        // 获得图像的字符流
                        InputStream is = conn.getInputStream();
                        BufferedInputStream bis = new BufferedInputStream(is, length);
                        bm[0] = BitmapFactory.decodeStream(bis);
                        bis.close();
                        is.close();// 关闭流
                        Message msg1=Message.obtain();
                        msg1.what=1234;
                        msg1.obj= bm[0];
                        handler.sendMessage(msg1);
                    }catch (Exception e){
                        e.printStackTrace();
                        Message msg1=Message.obtain();
                        msg1.what=1234;
                        msg1.obj= null;
                        handler.sendMessage(msg1);
                    }
                }
            }.start();

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Bitmap setBitMap(Bitmap src){
        int radius2 = src.getWidth() / 2;
        int radius1 = src.getHeight() / 2;
        int radius = radius2>radius1?radius1:radius2;
        BitmapShader bitmapShader = new BitmapShader(src, Shader.TileMode.REPEAT,
                Shader.TileMode.REPEAT);
        Bitmap dest = Bitmap.createBitmap(radius*2, radius*2, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(dest);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(bitmapShader);
        c.drawCircle(radius,radius, radius, paint);
        return dest;
    }
}
